#!/usr/bin/env python3
"""
Rules Guide Generator for Intelligent Rules V2.0
为用户项目生成规则指导和模板

Usage: python intelligent_rules_v2/tools/rules_guide_generator.py --type [web|ai|enterprise]
"""

import os
import sys
import argparse
import yaml
from pathlib import Path
from typing import Dict, List, Any, Optional

class RulesGuideGenerator:
    """规则指导生成器"""
    
    def __init__(self, user_project_root: Path = None):
        self.user_project_root = user_project_root or Path.cwd()
        self.intelligent_rules_path = self.user_project_root / "intelligent_rules_v2"
        
    def generate_rules_guide(self, project_type: str) -> Dict[str, Any]:
        """生成规则指导"""
        
        print(f"📜 为 {project_type} 项目生成规则指导")
        print("=" * 50)
        
        # 1. 创建规则目录结构
        self._create_rules_structure()
        
        # 2. 生成基础规则模板
        self._generate_base_rules_templates()
        
        # 3. 生成项目类型特定规则
        self._generate_project_specific_rules(project_type)
        
        # 4. 生成规则集成指南
        self._generate_integration_guide(project_type)
        
        # 5. 生成配置模板
        self._generate_config_templates(project_type)
        
        print("\n✅ 规则指导生成完成！")
        return {"status": "success", "project_type": project_type}
    
    def _create_rules_structure(self):
        """创建规则目录结构"""
        print("📁 创建规则目录结构...")
        
        rules_dirs = [
            "rules",
            "rules/core",
            "rules/evolution", 
            "rules/system",
            "rules/validation",
            "config"
        ]
        
        for dir_path in rules_dirs:
            full_path = self.user_project_root / dir_path
            full_path.mkdir(parents=True, exist_ok=True)
            print(f"✅ {dir_path}/")
    
    def _generate_base_rules_templates(self):
        """生成基础规则模板"""
        print("\n📋 生成基础规则模板...")
        
        # 生成核心业务规则模板
        core_rules_template = """# 用户项目核心业务规则
# 基于 intelligent_rules_v2 通用底座

rule_metadata:
  name: "用户项目核心业务规则"
  version: "1.0.0"
  category: "business_core"
  base_rules: "intelligent_rules_v2/rules/core"
  
# 引用通用底座规则
base_inheritance:
  source: "intelligent_rules_v2/rules/core"
  override_allowed: true
  extension_required: true

# 项目特定业务规则
business_rules:
  # 在这里定义您的业务规则
  domain_logic:
    validation: "custom_validation"
    processing: "domain_specific"
    
  data_management:
    persistence: "project_specific"
    caching: "optimize_for_domain"
    
  # 示例：用户管理规则
  user_management:
    authentication: "required"
    authorization: "role_based"
    session_management: "secure"
    
  # 示例：数据处理规则  
  data_processing:
    input_validation: "comprehensive"
    business_logic: "domain_driven"
    output_formatting: "standardized"

# 与底座规则的集成
integration_with_base:
  rule_precedence: "user_rules_first"
  conflict_resolution: "explicit_override"
  fallback_to_base: true
"""
        
        with open(self.user_project_root / "rules" / "core" / "business_rules.yaml", "w", encoding='utf-8') as f:
            f.write(core_rules_template)
        
        # 生成演进规则模板
        evolution_rules_template = """# 用户项目演进规则
# 定义项目特定的演进策略

rule_metadata:
  name: "用户项目演进规则"
  version: "1.0.0"
  category: "evolution"
  base_rules: "intelligent_rules_v2/rules/evolution"

# 项目演进策略
evolution_strategy:
  # 演进触发条件
  triggers:
    code_quality_threshold: 85
    performance_degradation: 10
    business_requirement_change: true
    
  # 演进范围
  scope:
    code_refactoring: "continuous"
    architecture_adjustment: "periodic"
    rule_optimization: "adaptive"
    
  # 演进验证
  validation:
    automated_testing: "mandatory"
    performance_benchmarking: "required"
    business_validation: "stakeholder_approval"

# 实践驱动演进
practice_driven_evolution:
  # 实践收集
  practice_collection:
    development_patterns: "automated_analysis"
    problem_patterns: "issue_tracking"
    solution_patterns: "success_documentation"
    
  # 规则提炼
  rule_refinement:
    effectiveness_threshold: 0.8
    consistency_requirement: "high"
    documentation_standard: "comprehensive"

# 与底座演进的协调
coordination_with_base:
  authority_level: "domain_specific"
  base_consultation: "required_for_architecture"
  conflict_resolution: "domain_expertise_priority"
"""
        
        with open(self.user_project_root / "rules" / "evolution" / "project_evolution.yaml", "w", encoding='utf-8') as f:
            f.write(evolution_rules_template)
        
        print("✅ 基础规则模板已生成")
    
    def _generate_project_specific_rules(self, project_type: str):
        """生成项目类型特定规则"""
        print(f"\n🎯 生成 {project_type} 项目特定规则...")
        
        if project_type == "web":
            self._generate_web_rules()
        elif project_type == "ai":
            self._generate_ai_rules()
        elif project_type == "enterprise":
            self._generate_enterprise_rules()
        else:
            print(f"⚠️ 未知项目类型: {project_type}")
    
    def _generate_web_rules(self):
        """生成Web项目特定规则"""
        
        web_rules = """# Web项目特定规则
# 继承 intelligent_rules_v2/modules/web_module 规则

rule_metadata:
  name: "Web项目规则"
  version: "1.0.0"
  category: "web_application"
  base_rules: "intelligent_rules_v2/modules/web_module"

# Web应用架构规则
web_architecture:
  frontend:
    framework: "react"  # 或 vue, angular
    state_management: "required_for_complex_apps"
    routing: "client_side_routing"
    
  backend:
    framework: "fastapi"  # 或 django, flask
    api_design: "restful"
    database: "postgresql"
    
  integration:
    cors_policy: "restrictive"
    api_versioning: "semantic"
    error_handling: "standardized"

# Web安全规则
web_security:
  authentication:
    method: "jwt_with_refresh"
    session_management: "stateless"
    
  authorization:
    access_control: "role_based"
    api_protection: "mandatory"
    
  data_protection:
    input_validation: "comprehensive"
    output_sanitization: "automatic"
    csrf_protection: "enabled"

# Web性能规则
web_performance:
  frontend_optimization:
    bundling: "code_splitting"
    caching: "aggressive_static_assets"
    lazy_loading: "images_and_components"
    
  backend_optimization:
    database_queries: "optimized"
    caching_strategy: "multi_level"
    response_compression: "enabled"

# 与底座Web模块的集成
integration_with_web_module:
  rule_inheritance: "full"
  customization_allowed: true
  override_with_justification: true
"""
        
        with open(self.user_project_root / "rules" / "core" / "web_specific_rules.yaml", "w", encoding='utf-8') as f:
            f.write(web_rules)
    
    def _generate_ai_rules(self):
        """生成AI项目特定规则"""
        
        ai_rules = """# AI/ML项目特定规则
# 基于 intelligent_rules_v2 通用底座指导

rule_metadata:
  name: "AI/ML项目规则"
  version: "1.0.0"
  category: "ai_ml_application"
  base_rules: "intelligent_rules_v2/rules/core"

# AI/ML开发规则
ml_development:
  data_management:
    version_control: "dvc"
    quality_validation: "automated"
    privacy_protection: "gdpr_compliant"
    
  model_development:
    experiment_tracking: "mlflow"
    reproducibility: "seed_controlled"
    validation_strategy: "cross_validation"
    
  model_deployment:
    containerization: "docker"
    monitoring: "real_time"
    rollback_strategy: "automated"

# AI/ML质量规则
ml_quality:
  code_standards:
    structure: "modular_pipelines"
    documentation: "comprehensive"
    testing: "unit_and_integration"
    
  model_quality:
    performance_thresholds: "domain_specific"
    fairness_validation: "required"
    explainability: "business_requirement"

# AI/ML安全规则
ml_security:
  data_security:
    encryption: "at_rest_and_transit"
    access_control: "role_based"
    audit_logging: "comprehensive"
    
  model_security:
    adversarial_testing: "required"
    model_versioning: "immutable"
    inference_monitoring: "anomaly_detection"

# 与通用底座的集成
integration_with_foundation:
  rules_inheritance: "core_foundation"
  custom_implementations: "domain_specific"
  performance_optimization: "ai_ml_focused"
"""
        
        with open(self.user_project_root / "rules" / "core" / "ai_specific_rules.yaml", "w", encoding='utf-8') as f:
            f.write(ai_rules)
    
    def _generate_enterprise_rules(self):
        """生成企业级项目特定规则"""
        
        enterprise_rules = """# 企业级项目特定规则
# 基于 intelligent_rules_v2 通用底座指导

rule_metadata:
  name: "企业级项目规则"
  version: "1.0.0"
  category: "enterprise_application"
  base_rules: "intelligent_rules_v2/rules/core"

# 企业级架构规则
enterprise_architecture:
  microservices:
    service_boundaries: "domain_driven"
    communication: "event_driven"
    data_consistency: "eventual_consistency"
    
  scalability:
    horizontal_scaling: "preferred"
    load_balancing: "automatic"
    resource_optimization: "continuous"
    
  reliability:
    fault_tolerance: "graceful_degradation"
    disaster_recovery: "automated"
    monitoring: "comprehensive"

# 企业级安全规则
enterprise_security:
  zero_trust:
    verification: "continuous"
    access_control: "least_privilege"
    network_segmentation: "micro_segmentation"
    
  compliance:
    audit_requirements: "sox_gdpr_compliant"
    data_governance: "enterprise_policy"
    security_scanning: "automated"

# 企业级质量规则
enterprise_quality:
  development_process:
    code_review: "mandatory"
    testing_coverage: "minimum_80_percent"
    deployment_gates: "quality_gates"
    
  operational_excellence:
    monitoring: "full_stack"
    alerting: "intelligent"
    performance_sla: "defined_and_monitored"

# 与通用底座的集成
integration_with_foundation:
  governance_inheritance: "enterprise_standards"
  compliance_requirements: "foundation_guided"
  customization_scope: "enterprise_focused"
"""
        
        with open(self.user_project_root / "rules" / "core" / "enterprise_specific_rules.yaml", "w", encoding='utf-8') as f:
            f.write(enterprise_rules)
    
    def _generate_integration_guide(self, project_type: str):
        """生成集成指南"""
        print("\n📖 生成集成指南...")
        
        integration_guide = f"""# 项目与 Intelligent Rules V2.0 集成指南

## 项目信息
- 项目类型: {project_type}
- 底座版本: V2.0
- 生成时间: {self._get_current_time()}

## 集成架构

```
{self.user_project_root.name}/
├── intelligent_rules_v2/      # 通用底座子模块
│   ├── foundation/            # 核心引擎
│   ├── rules/                 # 通用规则
│   └── modules/               # 专业模块
├── rules/                     # 项目专属规则
│   ├── core/                  # 核心业务规则
│   ├── evolution/             # 演进规则
│   ├── system/                # 系统规则
│   └── validation/            # 验证规则
├── config/                    # 项目配置
└── src/                       # 项目源码
```

## 规则层次结构

1. **通用底座规则** (intelligent_rules_v2/rules/)
   - 提供企业级标准和最佳实践
   - 所有项目共享的通用规则

2. **专业模块规则** (intelligent_rules_v2/modules/{project_type}_module/)
   - 特定领域的专业规则
   - 技术栈特定的指导

3. **项目专属规则** (rules/)
   - 项目特定的业务逻辑规则
   - 覆盖或扩展底座规则

## 使用方法

### 1. 运行智能演进引擎
```bash
python intelligent_rules_v2/foundation/core/intelligent_evolution_engine.py
```

### 2. 验证集成状态
```bash
python intelligent_rules_v2/tools/integration_validator.py
```

### 3. 检查规则冲突
```bash
python intelligent_rules_v2/foundation/core/rules_conflict_analyzer.py
```

### 4. 优化规则结构
```bash
python intelligent_rules_v2/foundation/core/rules_optimizer.py
```

## 最佳实践

1. **定期同步底座更新**
   ```bash
   git submodule update --remote intelligent_rules_v2
   ```

2. **项目规则应引用底座规则**
   ```yaml
   base_rules: "intelligent_rules_v2/rules/core"
   ```

3. **使用演进引擎持续优化**
   - 定期运行演进引擎
   - 基于实践反馈调整规则

4. **遵循规则层次原则**
   - 项目规则专注于业务逻辑
   - 技术规则继承底座标准
   - 必要时显式覆盖底座规则

## 故障排除

### 常见问题
1. **子模块更新问题**
   ```bash
   git submodule sync
   git submodule update --init --recursive
   ```

2. **规则冲突**
   - 运行冲突分析器
   - 明确规则优先级
   - 使用显式覆盖

3. **演进引擎失败**
   - 检查Python依赖
   - 验证配置文件格式
   - 查看日志文件

## 支持资源

- 底座文档: intelligent_rules_v2/docs/
- 示例项目: intelligent_rules_v2/examples/
- 社区支持: GitHub Issues
"""
        
        with open(self.user_project_root / "INTEGRATION_GUIDE.md", "w", encoding='utf-8') as f:
            f.write(integration_guide)
    
    def _generate_config_templates(self, project_type: str):
        """生成配置模板"""
        print("\n⚙️ 生成配置模板...")
        
        # 生成项目配置
        project_config = f"""# 项目配置文件
# 与 intelligent_rules_v2 通用底座集成

project:
  name: "{self.user_project_root.name}"
  version: "1.0.0"
  type: "{project_type}"
  description: "基于 intelligent_rules_v2 的{project_type}项目"

# 底座集成配置
intelligent_rules:
  version: "2.0.0"
  integration_mode: "submodule"
  
  # 应用的规则分类
  rule_categories:
    - "core"
    - "system" 
    - "evolution"
    - "{project_type}_specific"
  
  # 演进配置
  evolution:
    enabled: true
    auto_optimization: true
    practice_driven: true
    feedback_collection: true
    
  # 规则配置
  rules:
    custom_rules_path: "rules/"
    validation_level: "strict"
    auto_conflict_resolution: true
    
  # 质量配置
  quality:
    code_standards: "enterprise"
    security_level: "high"
    performance_targets: "{project_type}_optimized"

# 项目特定配置
{project_type}_config:
  # 在这里添加项目特定的配置
  pass
"""
        
        with open(self.user_project_root / "config" / "project.yaml", "w", encoding='utf-8') as f:
            f.write(project_config)
        
        print("✅ 配置模板已生成")
    
    def _get_current_time(self) -> str:
        """获取当前时间字符串"""
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

def main():
    """主程序"""
    parser = argparse.ArgumentParser(description="生成项目规则指导")
    parser.add_argument("--type", choices=["web", "ai", "enterprise"], 
                       default="web", help="项目类型")
    parser.add_argument("--project-root", type=Path, 
                       help="用户项目根目录")
    
    args = parser.parse_args()
    
    print("🔧 Intelligent Rules V2.0 规则指导生成器")
    print()
    
    generator = RulesGuideGenerator(args.project_root)
    result = generator.generate_rules_guide(args.type)
    
    if result["status"] == "success":
        print(f"\n🎉 {args.type} 项目规则指导生成完成！")
        print("\n📋 下一步:")
        print("1. 查看生成的规则文件并根据需要自定义")
        print("2. 运行集成验证: python intelligent_rules_v2/tools/integration_validator.py") 
        print("3. 启动智能演进: python intelligent_rules_v2/foundation/core/intelligent_evolution_engine.py")
        sys.exit(0)
    else:
        print("❌ 规则指导生成失败")
        sys.exit(1)

if __name__ == "__main__":
    main() 